package com.baidu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @author ShiLei
 * @version v1.0
 * @date 2020-03-17 17:58
 */
@Service
public class PaymentService {

    // 服务降级 **************************************

    /**
     * 成功方法
     *
     * @param id
     * @return
     */
    public String paymentInfo_OK(Integer id) {
        return "线程池：  " + Thread.currentThread().getName() + " paymentInfo_OK ,id: " + id + "" + "\t" + "成功";
    }

    /**
     * 有可能失败方法演示服务降级
     * HystrixCommand 注解表示该方法出现问题时服务降级该去找哪个方法进行处理
     * HystrixProperty 表示当前线程在什么时间断内运行属于正常运行
     *
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "handler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String paymentInfo_TimeOut(Integer id) {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：  " + Thread.currentThread().getName() + " paymentInfo_TimeOut ,id: " + id + "" + "\t" + "耗费3秒钟";
    }

    public String handler(Integer id) {
        return "线程池：  " + Thread.currentThread().getName() + " 8001访问超时，请重新尝试 ,id: " + id + "/(ㄒoㄒ)/~~";

    }


    // 服务熔断 **************************************

    /**
     *
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "paymentCicuitBreakerFallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //时间范围
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //失败率达到多少时短路
    })
    public String paymentCicuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("***id 不能为负数");
        }
        String s = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功,流水号： " + s;
    }

    public String paymentCicuitBreakerFallback(@PathVariable("id") Integer id) {
        return "id 不能为负数,请稍后再试 ： id" + id;
    }


}
